<template>
  <div>
    <!-- from卡片 -->
    <n-card :bordered="false" class="fromCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <!-- table卡片 -->
    <n-card :bordered="false" class="tableCard">
      <BasicTable
        :bordered="false"
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
      >
        <template #tableTitle>
          <div
            style="
              border: 2px solid #2d8cf0;
              height: 32px;
              margin-right: 5px;
              background-color: #2d8cf0;
            "
          ></div>
          <p style="font-size: 15px">交易管理表格</p>
        </template>
      </BasicTable>
    </n-card>
    <!-- 退款模态框 -->
    <n-modal v-model:show="showRefund" :show-icon="false" preset="dialog" title="发起退款">
      <n-form
        inline
        :label-width="80"
        :rules="rules"
        :size="size"
        ref="formRef"
        :modal="refundtext"
      >
        <n-grid x-gap="12" :cols="2">
          <n-gi style="margin-bottom: 18px">
            <n-form-item label="订单金额">
              <n-input readonly v-model:value="refundtext.payAmt" disabled> </n-input>
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 18px">
            <n-form-item label="退款金额" path="refundAmt">
              <n-input
                placeholder="请输入退款金额"
                v-model:value="refundtext.refundAmt"
                :on-change="amountCheck"
              />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 18px">
            <n-form-item label="会员号">
              <n-input disabled v-model:value="refundtext.memNo" />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 18px">
            <n-form-item label="商品订单号">
              <n-input disabled v-model:value="refundtext.prodOrdNo" />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 18px">
            <n-form-item label="收款订单号">
              <n-input disabled v-model:value="refundtext.payeeOrdNo" />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 18px">
            <n-form-item label="已退金额">
              <n-input disabled v-model:value="refundtext.totalRefundAmt" />
            </n-form-item>
          </n-gi>
        </n-grid>
      </n-form>
      <template #action>
        <n-space>
          <n-button
            type="info"
            :loading="formBtnLoading"
            @click="confirmForm"
            :disabled="changeType"
            >确定</n-button
          >
          <n-button @click="() => (showRefund = false)">取消</n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 查看模态框 -->
    <n-modal :show="showexamine">
      <n-card style="width: 800px" size="huge" :bordered="false">
        <n-grid x-gap="10" :cols="4" style="margin-bottom: 20px">
          <n-gi span="1">
            <p class="discount" style="margin-bottom: 10px">交易详情</p>
          </n-gi>
          <n-gi span="1"> </n-gi> <n-gi span="1"> </n-gi> <n-gi span="1"> </n-gi>
          <n-gi span="1">
            <n-form-item label="交易时间">
              <n-input disabled v-model:value="viewmodalInfo.createdTime" />
            </n-form-item>
          </n-gi>
          <n-gi span="1">
            <n-form-item label="交易流水">
              <n-input disabled v-model:value="viewmodalInfo.payeeOrdNo" />
            </n-form-item>
          </n-gi>
          <n-gi span="1">
            <n-form-item label="收款订单号">
              <n-input disabled v-model:value="viewmodalInfo.payeeOrdNo" />
            </n-form-item>
          </n-gi>
          <n-gi span="1">
            <n-form-item label="交易状态">
              <n-input disabled v-model:value="viewmodalInfo.status" />
            </n-form-item>
          </n-gi>
          <n-gi span="1">
            <n-form-item label="交易金额">
              <n-input disabled v-model:value="viewmodalInfo.txAmt" />
            </n-form-item>
          </n-gi>
          <!-- 原会员号 -->
          <n-gi span="1">
            <n-form-item label="交易币种">
              <n-input disabled v-model:value="viewmodalInfo.memNo" />
            </n-form-item>
          </n-gi>
          <n-gi span="1">
            <n-form-item label="会员号">
              <n-input disabled v-model:value="viewmodalInfo.memNo" />
            </n-form-item>
          </n-gi>

          <n-gi span="1"> </n-gi>
          <n-gi span="1">
            <p class="discount" style="margin-bottom: 10px">折扣详情</p>
          </n-gi>
          <n-gi span="1"> </n-gi> <n-gi span="1"> </n-gi> <n-gi span="1"> </n-gi>
          <n-gi span="1">
            <n-form-item label="折扣编码">
              <n-input disabled v-model:value="viewmodalInfo.disctNo" />
            </n-form-item>
          </n-gi>
          <n-gi span="1">
            <n-form-item label="折扣总额">
              <n-input disabled v-model:value="viewmodalInfo.disctAmt" />
            </n-form-item>
          </n-gi>
          <n-gi span="1">
            <n-form-item label="折扣发放时间">
              <n-input disabled v-model:value="viewmodalInfo.disctTime" />
            </n-form-item>
          </n-gi>
          原会员号。
          <n-gi span="1">
            <n-form-item label="折扣币种">
              <n-input disabled v-model:value="viewmodalInfo.memNo" />
            </n-form-item>
          </n-gi>
          <n-gi span="1">
            <n-form-item label="用户金额">
              <n-input disabled v-model:value="viewmodalInfo.memAmt" />
            </n-form-item>
          </n-gi>
          <n-gi span="1">
            <n-form-item label="平台金额">
              <n-input disabled v-model:value="viewmodalInfo.platformAmt" />
            </n-form-item>
          </n-gi>
          <n-gi span="1">
            <n-form-item label="推荐人金额">
              <n-input disabled v-model:value="viewmodalInfo.recommendAmt" />
            </n-form-item>
          </n-gi>
          <n-gi span="1"> </n-gi>
          <n-gi span="1"> <p class="discount">退款信息</p> </n-gi>
          <n-gi span="1"> </n-gi> <n-gi span="1"> </n-gi> <n-gi span="1"> </n-gi>
        </n-grid>
        <n-table :bordered="false" :single-line="false">
          <thead>
            <tr>
              <th>退款日期</th>
              <th>退款发起方</th>
              <th>退款金额</th>
              <th>币种</th>
              <th>退款流水号</th>
              <th>状态</th>
              <th>折扣退还金额</th>
              <th>币种</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(val, key) in viewmodalInfo.TxnRefundInfo" :key="key">
              <!-- 退款日期 -->
              <td>{{ val.refundDte }}</td>
              <!-- 退款发起方 -->
              <td>{{ val.refundApplicant }}</td>
              <!-- 退款金额 -->
              <td>{{ val.refundAmt }}</td>
              <!-- 币种 -->
              <td>{{ val.ccy }}</td>
              <!-- 退款流水 -->
              <td>{{ val.refundOrdNo }}</td>
              <!-- 退款状态 -->
              <td>{{ val.status }}</td>
              <!-- 折扣退还金额 -->
              <th>{{ val.disRefundAmt }}</th>
              <!-- 币种 -->
              <td>{{ val.ccy }}</td>
            </tr>
          </tbody>
        </n-table>
        <template #action>
          <n-space class="viewButton">
            <n-button type="info" :loading="formBtnLoading" @click="() => (showexamine = false)"
              >确定</n-button
            >
          </n-space>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { h, reactive, ref } from 'vue';
import { useMessage } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, useForm } from '@/components/Formtrage/index';
import { getTableList } from '@/api/table/list';
import { columns } from './columns';
import { PlusOutlined } from '@vicons/antd';
import { useRouter } from 'vue-router';
import { tradeListApi } from '@/api/trade/list';
import { initiateRefund } from '@/api/refundapply/Initiate';
import { tradeInfoApi } from '@/api/trade/info';
import formatDate from '@/utils/timestamp';

import { createStorage } from '@/utils/Storage';

const Storage = createStorage({ storage: localStorage });
const changeType = ref(false);
const moneyRule = (x) => x > 0 && x <= refundtext.value.payAmt;
const tradeListparm = ref({
  memNo: '',
  startTime: '',
  endTime: '',
  status: '',
  txNo: '',
  prodOrdNo: '',
  refundStatus: '',
  withdrawMethod: '',
  pageNum: 1,
  pageSize: 10,
});

// 获取交易管理列表
const jurisdiction = ref({});
const loadDataTable = async (res) => {
  console.log(res);
  tradeListparm.value.pageNum = res.page;
  tradeListparm.value.pageSize = res.pageSize;
  let data = await tradeListApi(tradeListparm.value);
  jurisdiction.value = data.data.body.list;
  data.data.body.list.forEach((val) => {
    val.createdTime = formatDate(new Date(val.createdTime));
    if (val.txTpe == '00') {
      val.txTpe = '提现';
    } else if (val.txTpe == '01') {
      val.txTpe = '转账';
    } else if (val.txTpe == '02') {
      val.txTpe = '支付';
    } else if (val.txTpe == '03') {
      val.txTpe = '退款';
    } else {
      val.txTpe = '无';
    }
    if (val.status == '0') {
      val.status = '待支付';
    } else if (val.status == '1') {
      val.status = '已支付';
    } else if (val.status == '2') {
      val.status = '失效';
    } else {
      val.status = '无';
    }
    if (val.refundStatus == true) {
      val.refundStatus = '已有退款';
    } else {
      val.refundStatus = '无记录';
    }
  });
  let datas = {
    list: data.data.body.list,
    page: data.data.body.page,
    pageSize: data.data.body.pageSize,
    pageCount: Math.ceil(data.data.body.total / res.pageSize),
  };
  console.log(datas);
  return datas;
};

const schemas = [
  {
    field: 'makeDate',
    component: 'NDatePicker',
    label: '交易日期：',
    componentProps: {
      type: 'daterange',
      clearable: true,
      onUpdateValue: (e) => {
        tradeListparm.value.startTime = e[0];
        tradeListparm.value.endTime = e[1];
        console.log(e);
      },
    },
  },
  {
    field: 'prodOrdNo',
    component: 'NInput',
    label: '商品订单号：',
    componentProps: {
      actions: ['clear'],
      placeholder: '请输入商品订单号',
      maxlength: 20,
      onInput: (e: any) => {
        tradeListparm.value.prodOrdNo = e;
      },
    },
  },
  {
    field: 'memNo',
    component: 'NInput',
    label: '会员号：',
    componentProps: {
      maxlength: 20,
      placeholder: '请输入会员号',
      onInput: (e: any) => {
        tradeListparm.value.memNo = e;
        console.log(e);
      },
    },
  },
  {
    field: 'status',
    component: 'NSelect',
    label: '交易状态：',
    componentProps: {
      placeholder: '请选择交易状态',
      options: [
        {
          label:'全部',
          value:''
        },
        {
          label: '待支付',
          value: 0,
        },
        {
          label: '已支付',
          value: 1,
        },
        {
          label: '失效',
          value: 2,
        },
      ],
      onUpdateValue: (e: any) => {
        tradeListparm.value.status = e;
        console.log(e);
      },
    },
  },
  {
    field: 'refundStatus',
    component: 'NSelect',
    label: '有无退款：',
    componentProps: {
      placeholder: '请选择',
      options: [
         {
          label: '全部',
          value: '',
        },
        {
          label: '有退款',
          value: true,
        },
        {
          label: '无退款',
          value: false,
        },
       
      ],
      onUpdateValue: (e: any) => {
        tradeListparm.value.refundStatus = e;
        console.log(e);
      },
    },
  },
  {
    field: 'txNo',
    component: 'NInput',
    label: '交易流水：',
    componentProps: {
      maxlength: 20,
      placeholder: '请输入交易流水',
      onInput: (e: any) => {
        tradeListparm.value.txNo = e;
        console.log(e);
      },
    },
  },
];

const router = useRouter();
const formRef: any = ref(null);
const message = useMessage();
const actionRef = ref();

const showRefund = ref(false);
const showexamine = ref(false);
const formBtnLoading = ref(false);
const formParams = reactive({
  name: '',
  address: '',
  date: null,
});

const params = ref({
  pageSize: 5,
  name: 'xiaoMa',
});

let authorityJson = Storage.get('OPERATORLIST');
const authority = JSON.parse(authorityJson);

// 列表行为
const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'button',
      actions: [
        {
          label: '退款',
          text: true,
          color: '#2d8cf0',
          onClick: handrefund.bind(null, record),
          ifShow: () => {
            csNumOne++;
            if (jurisdiction.value[csNumOne].status !== '待支付') {
              return authority.includes('MerRefund');
            } else {
              return false;
            }
          },
        },
        {
          label: '查看',
          text: true,
          color: '#2d8cf0',
          onClick: handexamine.bind(null, record),
          ifShow: () => {
            return authority.includes('viewTradeInfo');
          },
        },
      ],
      select: (key) => {
        message.info(`您点击了，${key} 按钮`);
      },
    });
  },
});

const [register, {}] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});

function onCheckedRow(rowKeys) {
  console.log(rowKeys);
}

function reloadTable() {
  csNumOne = -1;
  csNumTwo = -1;
  csNumThree = -1;
  actionRef.value.reload();
}

let csNumOne = -1;
let csNumTwo = -1;
let csNumThree = -1;

const viewParm = ref({
  prodOrdNo: '',
});

const viewmodalInfo = ref({
  createdTime: '',
  disctAmt: '',
  disctNo: '',
  disctTime: '',
  memAmt: '',
  memNo: '',
  payeeOrdNo: '',
  platformAmt: '',
  recommendAmt: '',
  status: '',
  txAmt: '',
  TxnRefundInfo: [],
});

// 查看交易管理信息详情
function handexamine(record: Recordable) {
  viewParm.value.prodOrdNo = record.prodOrdNo;
  tradeInfoApi(viewParm.value).then((val) => {
    viewmodalInfo.value.createdTime = formatDate(new Date(val.data.body.createdTime));
    viewmodalInfo.value.disctAmt = val.data.body.disctAmt;
    viewmodalInfo.value.disctNo = val.data.body.disctNo;
    viewmodalInfo.value.disctTime = formatDate(new Date(val.data.body.disctTime));
    viewmodalInfo.value.memAmt = val.data.body.memAmt;
    viewmodalInfo.value.memNo = val.data.body.memNo;
    viewmodalInfo.value.payeeOrdNo = val.data.body.payeeOrdNo;
    viewmodalInfo.value.platformAmt = val.data.body.platformAmt;
    viewmodalInfo.value.recommendAmt = val.data.body.recommendAmt;
    viewmodalInfo.value.status = val.data.body.status;
    if (viewmodalInfo.value.status == '0') {
      viewmodalInfo.value.status = '待支付';
    } else if (viewmodalInfo.value.status == '1') {
      viewmodalInfo.value.status = '已支付';
    } else if (viewmodalInfo.value.status == '2') {
      viewmodalInfo.value.status = '失效';
    } else {
      viewmodalInfo.value.status = '未知';
    }
    viewmodalInfo.value.txAmt = val.data.body.txAmt;
    viewmodalInfo.value.TxnRefundInfo = val.data.body.refundInfos;
    viewmodalInfo.value.TxnRefundInfo.forEach((val) => {
      val.refundDte = formatDate(new Date(val.refundDte));
      if (val.status == '0') {
        val.status = '已退款';
      } else if (val.status == '1') {
        val.status = '未处理';
      } else if (val.status == '2') {
        val.status = '退款失败';
      } else if (val.status == '3') {
        val.status = '已拒绝';
      } else {
        val.status = '未知';
      }
    });
    console.log(viewmodalInfo.value.TxnRefundInfo);
  });
  showexamine.value = true;
}

// 商户主动退款
const refundtext = ref({});
function handrefund(record: Recordable) {
  showRefund.value = true;
  refundtext.value.refundAmt = '';
  refundtext.value.payAmt = record.payAmt;
  refundtext.value.memNo = record.memNo;
  refundtext.value.prodOrdNo = record.prodOrdNo;
  refundtext.value.payeeOrdNo = record.payeeOrdNo;
   refundtext.value.totalRefundAmt = record.totalRefundAmt;
  console.log(refundtext.value);
}

function amountCheck(val) {
  console.log(val);
  console.log(refundtext.value.payAmt);
  if (val <= 0) {
    message.info('退款金额必须不可为0');
    changeType.value = true;
  } else if (val > refundtext.value.payAmt) {
    message.info('退款金额不可大于订单金额');
    changeType.value = true;
  } else if ((val = null)) {
    message.info('请输入订单金额');
    changeType.value = true;
  } else {
    changeType.value = false;
  }
}

function confirmForm(e) {
  initiateRefund(refundtext.value).then((val) => {
    if (val.data.sysHead.retCd === 'NGOAPS-T-100001') {
      message.error('退款金额不可为空');
    } else if (val.data.sysHead.retCd === '000000') {
      message.success('退款成功');
      showRefund.value = false;
    } else {
      message.error('提现失败');
      refundtext.value.refundAmt = '';
    }
  });
}

function handleSubmit(values: Recordable) {
  reloadTable();
}

function handleReset(values: Recordable) {
  tradeListparm.value.memNo = '';
  tradeListparm.value.startTime = '';
  tradeListparm.value.endTime = '';
  tradeListparm.value.status = '';
  tradeListparm.value.txNo = '';
  tradeListparm.value.prodOrdNo = '';
  tradeListparm.value.refundStatus = '';
  tradeListparm.value.withdrawMethod = '';
  reloadTable();
}
</script>

<style lang="less" scoped>
.fromCard {
  margin-top: 12px;
  border: 1px solid rgb(226, 229, 229);
  margin-bottom: 8px;
}
.tableCard {
  border: 1px solid rgb(226, 229, 229);
}
.viewButton {
  margin-left: 650px;
}
.discount {
  font-size: 18px;
  margin-top: 15px;
}
</style>
